import express from 'express';
import { checkSchema, validationResult } from 'express-validator'  
import util from 'utility'
import jwt from 'jsonwebtoken';  

const router = express.Router();


// 新增的操作
router.post('/book/add',checkSchema({
    type: { notEmpty: true, errorMessage:'预约的类型不能为空'},
    docNo: { notEmpty: true, errorMessage:'病历号不能为空'},
    bookTime: { notEmpty: true, errorMessage:'预约的时间不能为空' },
    doctor: {notEmpty: true, errorMessage:'预约的医生不能为空' },
    lastTime:  {notEmpty: true, errorMessage:'预约的持续时间不能为空' },
}), async (req,res)=>{
    res.validator();  // 对于请求参数进行校验

    const { type, docNo, bookTime, doctor, lastTime ,mark} = req.body;

    const data = {
        type, 
        docNo, 
        bookTime: new Date(bookTime), 
        doctor, 
        lastTime
    }
    if(mark) data.mark = mark;


    await req.prisma.book.create({
        data
    })
    res.success('预约添加成功')

})

// 删除预约
router.post('/book/del', checkSchema({
    id: { notEmpty: true, errorMessage: '患者id不能为空'}
}),async (req,res)=>{
    res.validator();  // 对于请求参数进行校验

    const { id } = req.body;
    await req.prisma.book.delete({
        where:{
            id: Number(id)
        }
    })
    res.fail('删除成功')
})

// 修改预约信息
router.post('/book/update',checkSchema({
    id: {notEmpty: true, errorMessage:'id不能为空' },
}), async (req,res)=>{
    res.validator();  // 对于请求参数进行校验

    const { type, docNo, bookTime, doctor, lastTime ,mark, id} = req.body;

    const data = { }
    if(type) data.type = type;
    if(docNo) data.docNo = docNo;
    if(bookTime) data.bookTime = new Date(bookTime);
    if(doctor) data.doctor = doctor;
    if(lastTime) data.type = lastTime;
    if(mark) data.mark = mark;


    await req.prisma.book.update({
        data,
        where:{
            id
        }
    })
    res.success('预约修改成功')

})

// 获取预约信息
router.get('/book/info', checkSchema({
    id: { notEmpty: true, errorMessage: '请传入一个正确的id' },
}), async (req,res)=>{
    const { id } = req.query;
    const book = await  req.prisma.book.findFirst({
        where:{
            id
        },
        include:{
            patient: true, // 联表查询对应的用户信息
        },
      
    })
    res.success(book)
})

router.get('/book/list', async(req,res)=>{

    let { limit = 30, page =1,  } = req.query;
    limit = Number(limit)
    page = Number(page)

    const where = {};
 
    const list = await req.prisma.patient.findMany({
        where,
        skip: (page-1)* limit,
        take: limit, // 一次查询的数量
        orderBy: {
            id:'desc'
        }
    })  

    const count = await req.prisma.patient.count(); // 统计总数

    res.success({ list, count })
    
})


export default router;